// 挂载在全局对象window上面
// let wsServer = new WebSocket(
//   `ws://localhost:3001/sendMessages?userid=${localStorage.getItem('userid')}`
// )
let wsUrl = `ws://localhost:3001/sendMessages?userid=${localStorage.getItem(
  'userid'
)}`
// 心跳检测时长60s一次
const heartBeatTime = 3
// 创建一个ws连接
let wsServer = new WebSocket(wsUrl)
// 心跳检测
let heartCheck = {
  timeout: heartBeatTime * 1000, //  心跳检测时长
  timeoutObj: null, // 定时变量
  serverTimeoutObj: null,
  reset: function () {
    clearTimeout(this.timeoutObj)
    clearTimeout(this.serverTimeoutObj)
    this.start()
  },
  start: function () {
    var self = this
    this.timeoutObj = setTimeout(function () {
      console.log('定时器1，给服务器发HeartBeat')
      wsServer.send(JSON.stringify({type:'heart'}))
      self.serverTimeoutObj = setTimeout(function () {
        console.log('定时器2，close')
        wsServer.close() //如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
      }, self.timeout)
    }, this.timeout)
  },
}
// 初始化事件函数
function initEventHandle() {
    wsServer.onclose = function () {
      console.log('close')
      reconnect(wsUrl)
    }
    wsServer.onerror = function (err) {
      console.log('error')
      reconnect(wsUrl)
    }
    wsServer.onopen = function () {
      heartCheck.start()//心跳检测重置
      console.log(`heartCheck.reset().start() //心跳检测重置 onpen`)
    }
    wsServer.onmessage = function (msg) {
      console.log('message')
      //如果获取到消息，心跳检测重置
      heartCheck.reset() //拿到任何消息都说明当前连接是正常的
      console.log('//如果获取到消息，心跳检测重置')
    }
}

// 重连
function reconnect(url) {
  // 避免触发多次重连
  if (reconnect.lockReconnect) return
  reconnect.lockReconnect = true
  setTimeout(function () {
    //没连接上会一直重连，设置延迟避免请求过多
    createWebSocket(url)
    reconnect.lockReconnect = false
  }, 2000)
}
// 实例websocket
function createWebSocket(url) {
    try {
        if ('WebSocket' in window) {
            wsServer = new WebSocket(url)
            console.log(`'WebSocket' in window)`)
        } else {
            alert("当前浏览器不支持websocket协议,建议使用现代浏览器",3000)
        }
        initEventHandle();
    } catch (e) {
        reconnect(url);
    }
}
// initEventHandle()
window.wsServer = wsServer